package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.orderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;


import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: ReportServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Author: 葛龙
 * @Create 2025/3/10 11:13
 * @Version 1.0
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private orderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        final ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        final ArrayList<Double> turnoverList = new ArrayList<>(); //select sum(amount) from order where order_time >= beginTime and order_time < endTime and status = 5;
        for (LocalDate localDate : dateList) {
            final HashMap<Object, Object> map = new HashMap<>();
            //将年月日拓展至年月日时分秒的形式
            final LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);//设置某一天的起始时间
            final LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);//设置某一天的结束时间
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnOver = reportMapper.getTurnover(map);
            turnOver = turnOver == null ? 0.0 : turnOver;
            turnoverList.add(turnOver);
        }

        final TurnoverReportVO reportVO = TurnoverReportVO.builder().dateList(StringUtils.join(dateList, ",")).turnoverList(StringUtils.join(turnoverList, ",")).build();
        return reportVO;
    }

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        final ArrayList<LocalDate> localDates = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        final ArrayList<Integer> newUser = new ArrayList<>();
        final ArrayList<Integer> totalUser = new ArrayList<>();
        for (LocalDate date : localDates) {
            //select count(id) from user where create_time > beginTime and create_time < endTime
            final LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            final LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每日新增用户
            Integer newUserByUser = reportMapper.getUserCount(beginTime, endTime);
            newUser.add(newUserByUser);
            //查询总用户
            Integer totalUserByUser = reportMapper.getUserCount(null, endTime);
            totalUser.add(totalUserByUser);
        }
        final String dateList = StringUtils.join(localDates, ",");
        final String newUserList = StringUtils.join(newUser, ",");
        final String totalUserList = StringUtils.join(totalUser, ",");
        return UserReportVO.builder().dateList(dateList).totalUserList(totalUserList).newUserList(newUserList).build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        final ArrayList<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        } //select count(id) from orders where order_time > beginTime and order_time < endTime and stastus = 5
        final ArrayList<Integer> validOrderCountArray = new ArrayList<>();
        final ArrayList<Integer> orderCountArray = new ArrayList<>();
        for (LocalDate localDate : dates) {
            final LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            final LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //每日有效订单数
            Integer validOrderCount = reportMapper.getorderStatistics(beginTime, endTime, Orders.COMPLETED);
            //每日总订单数
            Integer orderCount = reportMapper.getorderStatistics(beginTime, endTime, null);
            validOrderCountArray.add(validOrderCount);
            orderCountArray.add(orderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountArray.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountArray.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;//考虑到分母可能为0
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dates, ","))
                .orderCountList(StringUtils.join(orderCountArray, ","))
                .validOrderCountList(StringUtils.join(validOrderCountArray, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询指定时间区间内的销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出30天之内的报表
     */
    @Override
    public void export(HttpServletResponse response) {
        LocalDate end = LocalDate.now().minusDays(1);//前一天
        LocalDate begin = LocalDate.now().minusDays(30);//前三十天

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//开始的最小值
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);//结束的最大值

        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //将模板文件转换成输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //根据提供好的模板文件创建excel对象
            final XSSFWorkbook xssfWorkbook = new XSSFWorkbook(inputStream);
            //获取sheeet
            final XSSFSheet sheet1 = xssfWorkbook.getSheet("Sheet1");
            XSSFRow row = sheet1.getRow(1);
            row.getCell(1).setCellValue(begin + "至" + end); //对excel表中的2行2列进行日期的填充
            //获得第4行
            row = sheet1.getRow(3);//row重新赋值
            //获取单元格，填充第四行数据
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获取第五行
            row = sheet1.getRow(4);//row重新赋值
            //获取单元格，，填充第五行数据
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);//当天时间（年月日）
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));//查询当天的营业统计额

                //准备明细数据
                row = sheet1.getRow(7 + i); //从第八行开始填充

                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            final ServletOutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);//将java文件以流的形式写出到浏览器，供客户下载
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

